package com.mryan.ps_gateway.filter;

import com.mryan.ps_common.entity.constant.PSConstant;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import javax.servlet.http.HttpServletRequest;

/**
 * @BelongsProject: ps_cloud
 * @BelongsPackage: com.mryan.ps_gateway.filter
 * @Author: Yan
 * @CreateTime: 2021-04-25 21:46
 * @Description:
 */
@Slf4j
@Component
public class PSGatewayRequestFilter extends ZuulFilter {
	@Override
	public String filterType() {
		//要在请求转发出去前添加请求头，所以这里指定为pre
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		//要等拿到上下文后进行过滤，而PreDecorationFilter（处理请求上下文供后续使用的）过滤器的优先级为5，所以这里指定为6
		return 6;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() throws ZuulException {
		RequestContext context = RequestContext.getCurrentContext();
		String serviceId = (String) context.get(FilterConstants.SERVICE_ID_KEY);

		HttpServletRequest request = context.getRequest();
		String host = request.getRemoteHost();
		String method = request.getMethod();
		String uri = request.getRequestURI();

		log.info("请求URI：{}，HTTP Method：{}，请求IP：{}，ServerId：{}", uri, method, host, serviceId);

		//往请求上下文的头部添加了Key为ZuulToken
		byte[] token = Base64Utils.encode((PSConstant.ZUUL_TOKEN_VALUE).getBytes());
		context.addZuulRequestHeader(PSConstant.ZUUL_TOKEN_HEADER, new String(token));
		return null;
	}
}
